const { ipcMain, BrowserWindow, app, screen } = require("electron");
const crypto = require('crypto');
const fs = require('fs');
const path = require('path');
const { parseToBase64 } = require('../utils/dicomUtils')

//是否是测试环境
const isDevelopment = !app.isPackaged;
//目前存在的window
const windows = {}
//窗口句柄
const eventHandlers = {}

module.exports = () => {

    //监听打开新的阅片窗口
    ipcMain.on('DCMVIEW-OPEN-WINDOW', (event, arg) => {
        const { width, height } = screen.getPrimaryDisplay().workAreaSize;
        const { path: p } = arg
        const patientName = decodeURIComponent(p).split('-')[4]
        const id = crypto.createHash('md5').update(p).digest('hex');
        if (windows[id]) {
            windows[id].focus()
            return
        }
        windows[id] = new BrowserWindow({
            titleBarStyle: "hidden",
            fullScreen: true,
            show: false,
            width,
            height,
            title:`阅片:${patientName}`,
            icon: path.join(__dirname, '../assets/logo.png'),
            webPreferences: {
                preload: path.join(__dirname, "../preload.js"),
                enableBlinkFeatures: 'SharedArrayBuffer',
            }
        })
        windows[id].once("ready-to-show", () => {
            windows[id].show();
        });
        if (isDevelopment) {
            windows[id].loadURL(path.join("http://localhost:3321", `v?p=${p}`));
        } else {
            windows[id].loadFile(path.join(__dirname, 'platform/index.html'), {
                hash: `v?p=${p}`,
            });
        }
        windows[id].webContents.openDevTools();
        windows[id].on("close", () => {
            windows[id] = null;
            eventHandlers[id] = null
        });
    })

    //监听打开新的阅片窗口
    ipcMain.on('DCMVIEW-OPEN-FILE', (event, arg) => {
        const { p } = arg
        eventHandlers[p] = event
        const dcmPath = decodeURIComponent(p)
        // console.log('dcmPath', dcmPath)
        const studyFileName = fs.readdirSync(dcmPath)[0];
        const seriesNameList = fs.readdirSync(path.join(dcmPath, studyFileName))
        // seriesNameList.sort((a, b) => Number(a) - Number(b))
        seriesNameList.sort()
        console.log('seriesNameList', seriesNameList)
        for (const [seriesIndex, seriesName] of seriesNameList.entries()) {
            // console.log('seriesName', seriesName)
            const fileList = fs.readdirSync(path.join(dcmPath, studyFileName, seriesName));
            // fileList.sort((a, b) => Number(a) - Number(b)) //TODO 后期进行排序现在先不做，先做一个假排序
            fileList.sort()
            console.log('fileList', seriesIndex,seriesName, fileList)
            for (const [instanceIndex, fileName] of fileList.entries()) {
                // console.log('fileName', fileName)
                // console.log('fileName', path.join(dcmPath, studyFileName, seriesName, fileName))
                const data = fs.readFileSync(path.join(dcmPath, studyFileName, seriesName, fileName))

                // const seriesIndex = Number(seriesName)
                let coverImg = undefined
                if (instanceIndex === 0) {
                    coverImg = parseToBase64(data)
                }
                event.reply('DCMVIEW-OPEN-FILE-CALL', { seriesIndex, instanceIndex, data, coverImg })
            }
        }
        event.reply('DCMVIEW-OPEN-FILE-CALL', { isComplete: true })
    })


}